#include "write_cgic.h"

int sem_p(int semid, int num)
{
	struct sembuf mybuf;
	mybuf.sem_num = num;
	mybuf.sem_op  = -1;
	mybuf.sem_flg = SEM_UNDO;
	if(semop(semid, &mybuf, 1) < 0){
		perror("semop");
		exit(1);
	}

	return 0;
}

int sem_v(int semid, int num)
{
	struct sembuf mybuf;
	mybuf.sem_num = num;
	mybuf.sem_op  = 1;
	mybuf.sem_flg = SEM_UNDO;
	if(semop(semid, &mybuf, 1) < 0){
		perror("semop");
		exit(1);
	}

	return 0;
}

void write_cgic(threshold_t *thld, struct Env *warehouse)
{
	key_t key;
	int shmid,semid;
	struct shm_addr *shm_buf = NULL;

	if((key = ftok("/app", 'i')) < 0){
		perror("ftok");
		exit(1);
	}

	if((semid = semget(key, 1, IPC_CREAT|0666)) < 0){
		perror("semget");
		exit(1);
	}

	if((shmid = shmget(key, 32, IPC_CREAT|0666)) == -1){
		perror("shmget");
		exit(1);
	}

	if((shm_buf = (struct shm_addr*)shmat(shmid, NULL, 0)) == (void *)-1){
		perror("shmat");
		exit(1);
	}

	sem_p(semid, 0);

	shm_buf->rt_status.storage_status = 1
	shm_buf->rt_status.temperature = warehouse->temp;

	sem_v(semid, 0);
}
